/**
 * 生成图片名称
 * dir 文件前缀
 * suffix 图片类型
 */
const createImgName = function (dir, suffix) {
    var name = '';
    let arr = dir.split('/')||[''];
    name = arr[arr.length-1] + '_' + new Date().getTime() + '.' + (suffix || 'png')

    return name;
}

let uploadFiles = async (imgList, dir) => {
    console.log(imgList, dir)
    let promiseAll = [];
    return new Promise(async function (resolve, reject) {
        for (let index = 0; index < imgList.length; index++) {
            let item = imgList[index];
            var url = await wxUploadFile(item, dir).catch(error => {
                wx.showModal({
                    content: '资源上传失败，请重新上传！',
                    showCancel: false
                })
                reject(error)
                wx.hideLoading()
            })
            promiseAll.push(url)
        }
        resolve(promiseAll)
    })
}
let wxUploadFile = (file, dir) => {
    return new Promise(function (resolve, reject) {
        wx.cloud.uploadFile({
            cloudPath: (dir || 'access') + '/' + createImgName(dir, 'png'),
            filePath: file, // 文件路径
        }).then(async res => {
            let fileList = await getTempFileURL([res.fileID])
            console.log("----fileList",fileList)
            resolve(fileList[0].tempFileURL)
        }).catch(error => {
            reject(error)
        });
    })
}
const getTempFileURL = (fileList)=>{
    return new Promise(function (resolve, reject) {
        wx.cloud.getTempFileURL({
            fileList: fileList
        }).then(res => {
            resolve(res.fileList)
        })
    })
}


export {
    uploadFiles
}